//
//  QuerenChongzhiViewController.m
//  customer
//
//  Created by 往返网络 on 17/8/22.
//  Copyright © 2017年 com. All rights reserved.
//

#import "QuerenChongzhiViewController.h"
#import "SuccedChongzhiViewController.h" //充值成功
#define return_tag 2000
#define min_h 80.0/H_BASE*SCREEN_H
//定义充值验证码URL
#define URL_GETCODE [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/payRechargeSendCode?type=get",BASE_URL]
//定义确认充值URL
#define URL_QUEREN [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/payRechargeConfig?type=get",BASE_URL]
@interface QuerenChongzhiViewController ()<UITextFieldDelegate>
@property (nonatomic,strong)UILabel * phonenumlab;
//开辟多线程定时器，在后台执行，比NSTimer更自然
@property (nonatomic,strong) dispatch_source_t timer;
@property (nonatomic,strong)AFHTTPSessionManager* manger;
@property (nonatomic,copy)NSString * sendcode; //点击发送验证码
@end

@implementation QuerenChongzhiViewController
{
    UITextField * messagetf;  //短信验证码
    UIButton * messbtn; // 获取验证码

}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self createUI];
    
    // Do any additional setup after loading the view.
}
- (void)loadTimer{
    
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [messbtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                [messbtn setTitleColor:COLORRGBA(255, 102, 102, 1) forState:UIControlStateNormal];
                messbtn.layer.cornerRadius = 2;
                messbtn.layer.borderColor = [COLORRGBA(255, 102, 102, 1)CGColor];
                messbtn.layer.borderWidth = 1;
                messbtn.clipsToBounds = YES;
                messbtn.backgroundColor = [UIColor whiteColor];
                messbtn.clipsToBounds = YES;

                messbtn.userInteractionEnabled = YES;
                
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果 %2d秒后重新发送
                [messbtn setTitle:[NSString stringWithFormat:@"已发送(%2ds)", seconds] forState:UIControlStateNormal];
                messbtn.layer.borderWidth = 0;
                messbtn.backgroundColor = COLORRGBA(238, 240, 239, 1);
                [messbtn setTitleColor:COLORRGBA(174, 174, 173, 1) forState:UIControlStateNormal];
                
                messbtn.userInteractionEnabled = NO;
            });
            time--;
            
        }
    });
    
    dispatch_resume(_timer);
    
    
}

- (void)createUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    float cornersize = 20;
    cornersize = SCREEN_H < 667 ? 18 : 22 ;

    float fontsize = 17;
    
    fontsize = SCREEN_H < 667 ? 15 : 19;
    
    if (SCREEN_H == 667) {
        
        fontsize = 17;
        cornersize = 20;

    }
    self.view.backgroundColor = COLORRGBA(239, 239, 239, 1);
    //设置表头
    UIView * titleview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 128.0/1334*SCREEN_H)];
    
    titleview.backgroundColor = COLORRGBA(7, 24, 57, 1);
    
    [self.view addSubview:titleview];
    
    //title
    UILabel * titlelab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20.0, SCREEN_W, 90.0/H_BASE*SCREEN_H)];
    titlelab.text = @"充值信息确认";
    
    titlelab.textColor = [UIColor whiteColor];
    
    [self.view addSubview:titlelab];
    
    titlelab.textAlignment = NSTextAlignmentCenter;
    
    titlelab.font = [UIFont systemFontOfSize:fontsize];
    
    UILabel * leftlable  = [[UILabel alloc]initWithFrame:CGRectMake(0, 20+14.0/1334*SCREEN_H, 150.0/W_BASE*SCREEN_W, 60.0/1334.0*SCREEN_H)];
    leftlable.textAlignment = NSTextAlignmentCenter;
    NSString * endstr = @"\U0000e697";
    NSString * text = [NSString stringWithFormat:@"%@%@",endstr,@"返回"];
    leftlable.attributedText = [self changeLabelWithText2:text andStartplace:endstr andendplae:nil andfontsize:fontsize-2];
    leftlable.textColor = [UIColor whiteColor];
    [self.view addSubview:leftlable];
    
    UIButton * returnbtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150.0/W_BASE*SCREEN_W, 150.0/H_BASE*SCREEN_H)];
    [returnbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    returnbtn.tag = return_tag;
    [self.view addSubview:returnbtn];
    
    UIView * backview = [[UIView alloc]initWithFrame:CGRectMake(0, 127.0/H_BASE*SCREEN_H, SCREEN_W, SCREEN_H-127.0/H_BASE*SCREEN_H)];
    backview.backgroundColor = COLORRGBA(239, 239, 239, 1);
    [self.view addSubview:backview];
    
    UIView * view1 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(titleview.frame)+30.0/H_BASE*SCREEN_H, SCREEN_W, min_h)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    
    UILabel * numlab = [[UILabel alloc]initWithFrame:CGRectMake(30.0/W_BASE*SCREEN_W, 0, 150.0/W_BASE*SCREEN_W,min_h )];
    numlab.text = @"手机号";
    numlab.textColor = COLORRGBA(102, 102, 102, 1);
    numlab.font = [UIFont systemFontOfSize:fontsize-2];
    [view1 addSubview:numlab];
    
    _phonenumlab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_W - 210.0/W_BASE*SCREEN_W, 0, 200.0/W_BASE*SCREEN_W, min_h)];
//    NSString  * phone = self.bankphonestr;
//    NSString * startstr = [phone substringToIndex:3];
//    NSString * endstring = [phone substringFromIndex:7];
//    _phonenumlab.textAlignment = NSTextAlignmentRight;
//    _phonenumlab.text  = [NSString stringWithFormat:@"%@****%@",startstr,endstring];
    _phonenumlab.text = self.bankphonestr; //银行返回的手机号
    _phonenumlab.font = [UIFont systemFontOfSize:fontsize-2];
    [view1 addSubview:_phonenumlab];

    UIView * view2 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(view1.frame)+30.0/H_BASE*SCREEN_H, SCREEN_W, min_h)];
    view2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view2];
    
    UILabel * yanlab = [[UILabel alloc]initWithFrame:CGRectMake(30.0/W_BASE*SCREEN_W, 0, 100.0/W_BASE*SCREEN_W,min_h )];
    yanlab.text = @"验证码";
    yanlab.textColor = COLORRGBA(102, 102, 102, 1);
    yanlab.font = [UIFont systemFontOfSize:fontsize-2];
    [view2 addSubview:yanlab];
    
    messagetf = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(yanlab.frame), 0, 200.0/W_BASE*SCREEN_W, min_h)];
    messagetf.font = [UIFont systemFontOfSize:fontsize-2];
    messagetf.delegate = self;
    messagetf.keyboardType = UIKeyboardTypeNumberPad;
    [view2 addSubview:messagetf];
    
    messbtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_W- 180.0/W_BASE*SCREEN_W, CGRectGetMinY(messagetf.frame)+10.0/H_BASE*SCREEN_H, 150.0/W_BASE*SCREEN_W, 60.0/H_BASE*SCREEN_H)];
    messbtn.layer.cornerRadius = 2;
    messbtn.layer.borderColor = [COLORRGBA(255, 102, 102, 1)CGColor];
    messbtn.layer.borderWidth = 1;
    messbtn.clipsToBounds = YES;
    messbtn.backgroundColor = [UIColor whiteColor];
    messbtn.clipsToBounds = YES;
    
    [messbtn setTitleColor:COLORRGBA(255, 102, 102, 1) forState:UIControlStateNormal];
    messbtn.titleLabel.font = [UIFont systemFontOfSize:fontsize - 5];
    
    [view2 addSubview:messbtn];
    
    [messbtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    
    messbtn.tag = 1000;
    
    [messbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton * confbtn = [[UIButton alloc]initWithFrame:CGRectMake(30.0/W_BASE*SCREEN_W, CGRectGetMaxY(view2.frame)+40.0/H_BASE*SCREEN_H, SCREEN_W-60.0/W_BASE*SCREEN_W, min_h)];
    confbtn.backgroundColor = COLORRGBA(59, 214, 117, 1);
    [confbtn setTitle:@"确认充值" forState:UIControlStateNormal];
    confbtn.titleLabel.font = [UIFont systemFontOfSize:fontsize-2];
    [self.view addSubview:confbtn];
    [confbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    confbtn.tag = 3000;
    confbtn.layer.cornerRadius = 2;
    confbtn.clipsToBounds = YES;
    [confbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark  -  -  起始地＋发货人名（终止地＋收货人名）格式化 － － －-- - -  -
-(NSMutableAttributedString*)changeLabelWithText2:(NSString*)needText andStartplace:(NSString *)startplace andendplae:(NSString *)endplace andfontsize:(float)fontsize
{
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:needText];
    NSInteger startlength = startplace.length;
    //起始格式化
    [attrString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"iconfont" size:fontsize+2] range:NSMakeRange(0,startlength)];
    //    //尾部格式化
    [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontsize] range:NSMakeRange(startlength , needText.length  - startlength)];
    return attrString;
}


#pragma mark - - - - - - - - - - -  Action - - - - - - - - - - - - -
- (void)enterClick:(UIButton *)btn{
    
    switch (btn.tag) {
        case return_tag:
            //返回
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case 1000:
            //获取验证码
            [self getYanzhengString];
            break;
            
        case 3000:
            //
            NSLog(@"确认，提交验证码是否正确，进入下一页");
            if (messagetf.text.length == 0) {
                ALERT(@"提示", @"验证码格式有误", self, @"确定", nil);
                return;
            }
            [messagetf resignFirstResponder];
            [self configChonzhi];
            messagetf.text = @"";

            break;
            
    }
}
#pragma mark  - -- - - 获取验证码- -- - - - - -

- (void)getYanzhengString{
    
    //字符串反转之后，再发送出去 phonenum --- 反转 －－－＊2 －－－ 转化为a-z
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
    
    NSString * url = [NSString stringWithFormat:@"%@&token=%@&money=%@",URL_GETCODE,token,self.jinestring];
    NSLog(@"充值验证码 url %@",url);
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"dict %@",dict);
            NSInteger code = [dict[@"code"]integerValue];
            if (code == 0) {
                NSLog(@"code 为0");
                //获取验证码成功 及相应充值参数
                NSDictionary * info = dict[@"info"];
                self.info = info;
                _sendcode = @"1";
                //发送短信
                [self loadTimer];
                
            }else{
                
                NSLog(@"get code no");
                
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
            }
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
    }];
    
}

- (void)configChonzhi{
    if (![_sendcode isEqualToString:@"1"]) {
        ALERT(@"提示", @"请获取验证码", self, @"确定", nil);
        return;
    }
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
    NSString * url = [NSString stringWithFormat:@"%@&token=%@&rechargeCode=%@",URL_QUEREN,token,messagetf.text];
    NSLog(@"确认充值 url %@",url);
    NSLog(@"+++++++++++self.info %@",_info);
    NSDictionary * param = @{@"OpenId":self.info[@"OpenId"],
                             @"amount":self.info[@"amount"],
                             @"customerId":self.info[@"customerId"],
                             @"masterId":self.info[@"masterId"],
                             @"orderId":self.info[@"orderId"],
                             @"paydate":self.info[@"paydate"]};
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:param options:0 error:nil];
    NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    url = [NSString stringWithFormat:@"%@&info=%@",url,jsonString];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSLog(@"%@", url);
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (responseObject) {
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSInteger code = [dict[@"code"]integerValue];
            if (code == 0) {
                NSLog(@"充值成功");
                SuccedChongzhiViewController * succedvc = [[SuccedChongzhiViewController alloc]init];
                succedvc.jinestring = self.jinestring;
                [self.navigationController pushViewController:succedvc animated:YES];
            }else if(code == 1){
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
            }
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
    }];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField endEditing:YES];
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [messagetf resignFirstResponder];
    
}
#pragma mark - - -- - - - 懒加载 ---- - -- - -

- (AFHTTPSessionManager*)manger{
    
    if (!_manger) {
        
        _manger = [AFHTTPSessionManager manager];
        
        _manger.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    }
    return _manger;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
